#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<string.h>

int main(){
    pthread_key_t  key;
    pid_t pid;
    int shmid;
    sem_t semid1,semid2;
    char *shmaddr=NULL;
    key=ftok("pth_sem2",110);
    shmaddr=shmget(key,100,IPC_CREAT|0600);
    sem_init(&semid1,1,1);
    sem_init(&semid2,1,0);
    pid=fork();
    if(pid){
        //parent
        sem_wait(&semid2);
        sem_wait(&semid1);
        shmaddr=(char *)shmat(shmid,NULL,0);
        printf("%s\n",shmaddr);
        shmdt(shmaddr);
        sem_post(&semid1);
        shmctl(shmid,IPC_RMID,NULL);
        sem_destroy(&semid1);
        sem_destroy(&semid2);
    }
    else {  
        sem_wait(&semid1);
        shmaddr=(char *)shmat(shmid,NULL,0);
        strcpy(shmaddr,"qwerty");
        shmdt(shmaddr);
        sem_post(&semid1);
        sem_post(semid2);
    }

    return 0;
}